package com.example.demo.handler;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.DataListener;

/**
 * websocket消息处理器
 */
public class MessageHandler {
    private SocketIOServer server;
    private RoomHandler roomHandler;
    public MessageHandler(SocketIOServer server){
        this.server = server;
        this.roomHandler = new RoomHandler(server);
    }

    //处理消息类型
    public void startListening(){
        //客户端连接时发送连接信息
        server.addConnectListener(client -> {
            //打印连接的客户端
            System.out.println("客户端连接：" + client.getSessionId());
            //发送消息
            server.getClient(client.getSessionId()).sendEvent("strat","欢迎连接到服务器");
        });
        //客户端断开连接时触发
        server.addDisconnectListener(client -> {
            //打印断开连接的客户端id
            System.out.println("客户端断开连接：" + client.getSessionId());
        });
        //客户端加入房间
        server.addEventListener("joinRoom",String.class, (client,roomId,ackRequest) -> {
            //客户端加入指定的房间
            client.joinRoom(roomId);
            //发送加入房间成功的消息给客户端
            client.sendEvent("成功加入当前群聊",roomId);
            //广播消息到当前房间所有的成员
            server.getRoomOperations(roomId).sendEvent("chat","加入群聊");
        });

        //向当前房间发送消息
        server.addEventListener("chat", String.class, (client,message,ackRequest) -> {
            System.out.println("收到来自"+client.getHandshakeData().getSingleUrlParam("roomId") +"房间的消息：" + message);
            //获取当前客户端所在的房间
            String roomId = client.getHandshakeData().getSingleUrlParam("roomId");
            //向当前房间的所有成员广播消息
            server.getRoomOperations(roomId).sendEvent("chat",message);
        });
    }
}
